<template>
  <div class="app-container">
    <el-row :gutter="20">
     <!-- &lt;!&ndash;部门数据&ndash;&gt;
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>-->


      <!--用户数据-->
      <el-col :span="24" :xs="24">

        <!-- 查询区域 开始 -->
       <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
         <!--    <el-form-item label="员工" prop="employeeId">
              <el-input
                v-model="queryParams.employeeName"
                placeholder="请输入员工姓名"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->


        <el-form-item label="归属部门" prop="deptId">
          <treeselect style="width: 200px"
                      :disabled="isHiddenOrReadOnly"
                      v-model="queryParams.deptId"
                      :options="deptOptions"
                      placeholder="请选择归属部门" />
        </el-form-item>

         <!--根据月份自动生成默认考勤-->
         <el-form-item label="考勤月份" prop="attendanceDate">
           <el-date-picker clearable size="small" style="width: 200px;"
                           :disabled="isHiddenOrReadOnly"
                           v-model="chooseMonth"
                           type="month"
                           value-format="yyyy-MM"
                           placeholder="选择考勤月份">
           </el-date-picker>
         </el-form-item>
          <!--<el-form-item label="考勤月份" prop="attendanceDate">
            <el-date-picker clearable size="small" style="width: 200px"
                            v-model="queryParams.attendanceMonth"
                            type="month"
                            value-format="yyyy-MM"
                            placeholder="选择考勤月份">
            </el-date-picker>
          </el-form-item>-->

          <el-form-item>
            <el-button v-if="!isHiddenOrReadOnly" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <!--<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
            <el-button
              type="success"
              v-if="!isHiddenOrReadOnly"
              icon="el-icon-refresh"
              size="mini"
              @click="handleCreateDefault"
              v-hasPermi="['hr:attendance:export']"
            >生成默认考勤
            </el-button>


            <el-button
              type="danger"
              v-if="!isHiddenOrReadOnly"
              icon="el-icon-upload2"
              size="mini"
              @click="handleSubmitNext"
              v-hasPermi="['hr:attendance:export']"
            >提交
            </el-button>

          </el-form-item>
        </el-form>

        <!-- 查询区域 结束 -->


        <!-- 查询区域 结束 -->
        <el-row :gutter="10" class="mb8">
          <!--<el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['hr:attendance:add']"
            >新增
            </el-button>
          </el-col>-->
          <!--<el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['hr:attendance:edit']"
            >修改
            </el-button>
          </el-col>-->
         <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['hr:attendance:remove']"
            >删除
            </el-button>
          </el-col>-->
         <!-- <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['hr:attendance:export']"
            >导出
            </el-button>
          </el-col>-->



        </el-row>

        <el-table
          class="list-table"
          v-loading="loading"
          :data="attendanceList"
          stripe
          size="small"
          fit
          highlight-current-row
          @selection-change="handleSelectionChange"
          style="width: 100%;">
          <el-table-column type="selection" width="55" align="center"/>
          <!--<el-table-column label="ID" align="center" prop="id"/>-->
          <el-table-column label="员工" align="center" prop="employeeName"/>
          <el-table-column label="应上天数" align="center" prop="dueDays"/>
          <el-table-column label="出勤天数" align="center" prop="attendanceDays"/>
          <el-table-column label="加班天数" align="center" prop="overtimeDays"/>
          <el-table-column label="事假天数" align="center" prop="leaveDays"/>
          <el-table-column label="病假天数" align="center" prop="diseaseDays"/>
          <el-table-column label="婚假天数" align="center" prop="weddingDays"/>
          <el-table-column label="丧假天数" align="center" prop="funeralDays"/>
          <el-table-column label="旷工天数" align="center" prop="absenteeismDays"/>
          <el-table-column label="最后更新日期" align="center" prop="attendanceDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.attendanceDate,'{y}年{m}月{d}日') }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['hr:attendance:edit']"
              >修改
              </el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改出勤对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form class="editInfo" ref="form" :inline="true" :model="form" :rules="rules" size="small"
               label-width="120px">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input style="color: #000;" disabled="true" v-model="form.employeeName" placeholder="请输入员工姓名"/>
        </el-form-item>
        <el-form-item label="应上天数" prop="dueDays">
          <el-input v-model.number="form.dueDays" placeholder="请输入应上天数"/>
        </el-form-item>
        <el-form-item label="出勤天数" prop="attendanceDays">
          <el-input v-model.number="form.attendanceDays" placeholder="请输入出勤天数"/>
        </el-form-item>
        <el-form-item label="加班天数" prop="overtimeDays">
          <el-input v-model.number="form.overtimeDays" placeholder="请输入加班天数"/>
        </el-form-item>
        <el-form-item label="事假天数" prop="leaveDays">
          <el-input v-model.number="form.leaveDays" placeholder="请输入事假天数"/>
        </el-form-item>
        <el-form-item label="病假天数" prop="diseaseDays">
          <el-input v-model.number="form.diseaseDays" placeholder="请输入病假天数"/>
        </el-form-item>
        <el-form-item label="婚假天数" prop="weddingDays">
          <el-input v-model.number="form.weddingDays" placeholder="请输入婚假天数"/>
        </el-form-item>
        <el-form-item label="丧假天数" prop="funeralDays">
          <el-input v-model.number="form.funeralDays" placeholder="请输入丧假天数"/>
        </el-form-item>
        <el-form-item label="旷工天数" prop="absenteeismDays">
          <el-input v-model.number="form.absenteeismDays" placeholder="请输入旷工天数"/>
        </el-form-item>
        <el-form-item label="最后更新日期" prop="attendanceDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.attendanceDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择考勤日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listAttendance,
    getAttendance,
    delAttendance,
    addAttendance,
    updateAttendance,
    exportAttendance,
    addCreateDefault,
    addAttendanceConfirm
  } from '@/api/hr/attendance'
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    components: { Treeselect },
    data() {
      return {
        chooseMonth : undefined,
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 出勤表格数据
        attendanceList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 部门树选项
        deptOptions: undefined,
        // 部门名称
        deptName: undefined,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          employeeName: undefined,
          dueDays: undefined,
          attendanceMonth: undefined,
          overtimeDays: undefined,
          leaveDays: undefined,
          diseaseDays: undefined,
          weddingDays: undefined,
          funeralDays: undefined,
          absenteeismDays: undefined,
          attendanceDate: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          employeeId: [
            { required: true, message: '员工id不能为空', trigger: 'blur' }
          ], dueDays: [
            { required: true, message: '应上天数不能为空', trigger: 'blur' }
          ], attendanceDays: [
            { required: true, message: '出勤天数不能为空', trigger: 'blur' }
          ], overtimeDays: [
            { required: true, message: '加班天数不能为空', trigger: 'blur' }
          ], leaveDays: [
            { required: true, message: '事假天数不能为空', trigger: 'blur' }
          ], diseaseDays: [
            { required: true, message: '病假天数不能为空', trigger: 'blur' }
          ], weddingDays: [
            { required: true, message: '婚假天数不能为空', trigger: 'blur' }
          ], funeralDays: [
            { required: true, message: '丧假天数不能为空', trigger: 'blur' }
          ], absenteeismDays: [
            { required: true, message: '旷工天数不能为空', trigger: 'blur' }
          ], attendanceDate: [
            { required: true, message: '考勤日期不能为空', trigger: 'blur' }
          ], createTime: [
            { required: true, message: '创建时间不能为空', trigger: 'blur' }
          ], updateTime: [
            { required: true, message: '更新时间不能为空', trigger: 'blur' }
          ]

        },
        //add by yyf on 2020-1-20
        isHiddenOrReadOnly : false
      }
    },
    watch: {
      // 根据名称筛选部门树
     /* deptName(val) {
        this.$refs.tree.filter(val)
      }*/
    },


    created() {
      //this.getList()
      this.getTreeselect()

      //如果是考勤页面点编辑进来的，就默认设置部门和考勤月份，并且查询具体考勤人员的数据
      if(this.$router.query){
        this.isHiddenOrReadOnly = true;
        this.queryParams.deptId = this.$router.query.deptId;
        this.chooseMonth = this.$router.query.attendanceMonth;
        this.getList();
      }else{
        //如果是考勤页面点填报按钮进来的，允许修改部门和考勤月份，显示生成按钮

      }

    },
    methods: {
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id
        this.getList()
      },
      /** 查询出勤列表 */
      getList() {
        this.loading = false; //方便测试，取消遮罩层
        this.queryParams.attendanceMonth = this.chooseMonth;
        listAttendance(this.queryParams).then(response => {
          this.attendanceList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          employeeId: undefined,
          dueDays: undefined,
          attendanceDays: undefined,
          overtimeDays: undefined,
          leaveDays: undefined,
          diseaseDays: undefined,
          weddingDays: undefined,
          funeralDays: undefined,
          absenteeismDays: undefined,
          attendanceDate: undefined,
          createTime: undefined,
          updateTime: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加出勤'
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        this.open = true
        this.title = '修改出勤'
        getAttendance(id).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改出勤'
        })


      },

      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateAttendance(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              addAttendance(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      /*handleDelete(row) {
        const ids = row.id || this.ids
        this.$confirm('是否确认删除出勤编号为"' + ids + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delAttendance(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },*/
      /** 导出按钮操作 */
      /*handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有出勤数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportAttendance(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },*/

      //add by yyf
      //提交本月考勤数据
      handleSubmitNext(){
        if(!this.chooseMonth){
          this.msgError('请选择月份！')
          return;
        }

        if(!this.queryParams.deptId){
          this.msgError('请选择部门！')
          return;
        }

        var that = this;


        this.$confirm('是否确认提交所有数据，注意，提交后将不能修改！！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {

          addAttendanceConfirm({
            attendanceMonth: that.chooseMonth,
            deptId: that.queryParams.deptId
          }).then(response => {

            if (response.code === 200) {
              that.msgSuccess('创建成功')

              //提交确认后，状态是已确认的将不可编辑
              //这边就重新加载列表，后台应该给我返回空（关联考勤主表，不能只能查询编辑中的详细数据给我）

              this.getList();

            } else {
              this.msgError(response.msg)
            }

          });

        });
      },


      //add by yyf
      //根据月份和部门编号，生成默认考勤
      handleCreateDefault() {
        if(!this.chooseMonth){
          this.msgError('请选择月份！')
          return;
        }

        if(!this.queryParams.deptId){
          this.msgError('请选择部门！')
          return;
        }

        var that = this;

          // 后台生成逻辑 还需要 插入一条记录到考勤确认表，状态是编辑中
          addCreateDefault({
            attendanceMonth : this.chooseMonth,
            deptId : this.queryParams.deptId
          }).then(response => {
            if (response.code === 200) {
              that.msgSuccess('创建成功')
              this.getList(); // 创建成功以后，查询刚刚生成的考勤默认数据，然后再一条一条编辑吧
            } else {
              this.msgError(response.msg)
            }
          })



      }
    }
  }
</script>
